import { BrowserWindow, BrowserWindowConstructorOptions, shell } from 'electron'
import { WindowTypes } from '@globalTypes/global'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import { WindowBoundTool } from '../composables/WindowBoundTool'

export class CommonWindow {
  // 窗口实例
  private win: BrowserWindow
  // 窗口位置工具实例
  private boundTool: WindowBoundTool

  constructor(
    param: BrowserWindowConstructorOptions,
    windowKey: string, // 窗口id，不能重复
    url?: string,
    defaultPosition?: WindowTypes.WindowPosition,
  ) {
    this.win = this.init(param, url)
    this.boundTool = new WindowBoundTool(this.win, windowKey, {
      x: defaultPosition ? defaultPosition.x : 0,
      y: defaultPosition ? defaultPosition.y : 0,
      width: param.width ? param.width : 0,
      height: param.height ? param.height : 0,
    }, param.center)
  }

  // 初始化方法，接收窗口构造参数和可选的URL, 创建并返回窗口实例
  private init(param: BrowserWindowConstructorOptions, url?: string) {
    // 创建一个新的BrowserWindow实例，并传入构造参数
    const win = new BrowserWindow({
      ...param, // 展开传入的参数
      webPreferences: {
        // 设置窗口的Web偏好
        preload: join(__dirname, '../preload/index.js'), // 预加载脚本路径
        sandbox: false // true会导致无法使用node
        // experimentalFeatures: true, // 启用实验特性
      }
    })
    // 阻止弹出新窗口
    win.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })
    if (param.alwaysOnTop) {
      // 设置窗口优先级始终在最上方
      win.setAlwaysOnTop(true, 'screen-saver')
    }
    // 设置窗口对应的页面
    let winUrl = ''
    if (url) {
      winUrl = url
    }
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      win.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + winUrl)
    } else {
      win.loadFile(join(__dirname, '../renderer/index.html'), {
        hash: winUrl
      })
    }
    // win.webContents.openDevTools() // 打开开发者工具
    return win
  }

  // 打开窗口
  show() {
    this.win.on('ready-to-show', () => {
      this.win.show()
    })
  }

  // 获取窗口
  getWindow() {
    return this.win
  }

  addWindowMoveEvent() {
    this.boundTool.initWinMoveEventListener()
  }

  addWindowCloseListener(callback: Function){
    this.getWindow().on('closed', () => {
      callback()
    })
  }
}
